package com.vx.ratingTool.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.vx.ratingTool.Player;
import com.vx.ratingTool.dao.abstr.PlayerDAO;

public class PlayerDAOimpl implements PlayerDAO {

	private SessionFactory sessionFactory;

	@Override
	@SuppressWarnings("deprecation")
	public void setUpFactory() throws Exception {
		// A SessionFactory is set up once for an application
		sessionFactory = new Configuration().configure() // configures settings
															// from
															// hibernate.cfg.xml
				.buildSessionFactory();
	}

	@Override
	public void tearDownFactory() throws Exception {
		if (sessionFactory != null) {
			sessionFactory.close();
		}
	}

	@Override
	public void save(Player player) {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(player);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void update(Player player) {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.update(player);
		session.getTransaction().commit();
		session.close();

	}

	@Override
	public void delete(Player player) {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(player);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public Player findById(int id) {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Player result = (Player) session.createQuery("from Player as p where p.id = :_id").setParameter("_id", id).uniqueResult();

		session.getTransaction().commit();
		session.close();

		return result;
	}

	@Override
	public void saveList(List<Player> players) {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		for (int i = 0; i < players.size(); i++) {
			session.save(players.get(i));
		}
		session.getTransaction().commit();
		session.close();

	}

	@Override
	public List<Player> GetListOfPlayers() {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		List<Player> result = session.createQuery("from Player").list();
		session.getTransaction().commit();
		session.close();

		return result;
	}

	@Override
	public void clearDatabase() {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.createQuery("delete Player").executeUpdate();
		session.getTransaction().commit();
		session.close();

	}

	@Override
	public void massUpdate(List<Player> players) {

		Session session = sessionFactory.openSession();
		session.beginTransaction();
		for (int i = 0; i < players.size(); i++) {
			session.update(players.get(i));
		}
		session.getTransaction().commit();
		session.close();

	}
}
